<template>
  <div class="finance-settlement">
    <!-- 结算统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon today">
              <el-icon><Calendar /></el-icon>
            </div>
            <div class="stat-details">
              <h3>¥{{ formatMoney(stats.todaySettlement) }}</h3>
              <p>今日结算</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon month">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-details">
              <h3>¥{{ formatMoney(stats.monthSettlement) }}</h3>
              <p>本月结算</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon pending">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-details">
              <h3>¥{{ formatMoney(stats.pendingAmount) }}</h3>
              <p>待结算金额</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon count">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-details">
              <h3>{{ stats.settlementCount }}</h3>
              <p>结算笔数</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="结算周期">
          <el-select v-model="searchForm.period" placeholder="请选择" clearable>
            <el-option label="日结算" value="daily" />
            <el-option label="周结算" value="weekly" />
            <el-option label="月结算" value="monthly" />
          </el-select>
        </el-form-item>
        <el-form-item label="结算状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="待结算" value="pending" />
            <el-option label="结算中" value="processing" />
            <el-option label="已结算" value="completed" />
            <el-option label="结算失败" value="failed" />
          </el-select>
        </el-form-item>
        <el-form-item label="结算时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="handleBatchSettle">
          <el-icon><CreditCard /></el-icon>
          批量结算
        </el-button>
        <el-button type="success" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 结算列表 -->
    <el-card class="table-card">
      <el-table 
        v-loading="loading" 
        :data="tableData" 
        border 
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="settlementId" label="结算ID" width="180" />
        <el-table-column prop="period" label="结算周期" width="100">
          <template #default="{ row }">
            <el-tag :type="getPeriodType(row.period)">
              {{ getPeriodText(row.period) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="120" />
        <el-table-column prop="endDate" label="结束日期" width="120" />
        <el-table-column prop="totalAmount" label="结算金额" width="120">
          <template #default="{ row }">
            <span class="amount-text">¥{{ formatMoney(row.totalAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderCount" label="订单数量" width="100" />
        <el-table-column prop="status" label="结算状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column prop="settleTime" label="结算时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleViewDetail(row)">
              详情
            </el-button>
            <el-button 
              v-if="row.status === 'pending'" 
              type="text" 
              size="small" 
              @click="handleSettle(row)"
            >
              结算
            </el-button>
            <el-button 
              v-if="row.status === 'failed'" 
              type="text" 
              size="small" 
              @click="handleRetry(row)"
            >
              重试
            </el-button>
            <el-button type="text" size="small" @click="handleExportDetail(row)">
              导出
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="loadTableData"
          @size-change="loadTableData"
        />
      </div>
    </el-card>

    <!-- 批量结算对话框 -->
    <el-dialog v-model="batchDialogVisible" title="批量结算" width="600px">
      <div class="batch-info">
        <p>已选择 <strong>{{ selectedRows.length }}</strong> 条结算记录</p>
        <p>总金额：<strong class="amount-text">¥{{ formatMoney(batchAmount) }}</strong></p>
      </div>
      <el-form :model="batchForm" label-width="100px">
        <el-form-item label="结算方式">
          <el-radio-group v-model="batchForm.method">
            <el-radio label="bank">银行转账</el-radio>
            <el-radio label="alipay">支付宝</el-radio>
            <el-radio label="wechat">微信支付</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="结算说明">
          <el-input v-model="batchForm.remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmBatchSettle" :loading="batchLoading">
          确认结算
        </el-button>
      </template>
    </el-dialog>

    <!-- 结算详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="结算详情" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="结算ID">{{ currentSettlement.settlementId }}</el-descriptions-item>
        <el-descriptions-item label="结算周期">{{ getPeriodText(currentSettlement.period) }}</el-descriptions-item>
        <el-descriptions-item label="开始日期">{{ currentSettlement.startDate }}</el-descriptions-item>
        <el-descriptions-item label="结束日期">{{ currentSettlement.endDate }}</el-descriptions-item>
        <el-descriptions-item label="结算金额">¥{{ formatMoney(currentSettlement.totalAmount) }}</el-descriptions-item>
        <el-descriptions-item label="订单数量">{{ currentSettlement.orderCount }}</el-descriptions-item>
        <el-descriptions-item label="结算状态">{{ getStatusText(currentSettlement.status) }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentSettlement.createTime }}</el-descriptions-item>
        <el-descriptions-item label="结算时间" :span="2">{{ currentSettlement.settleTime }}</el-descriptions-item>
      </el-descriptions>
      
      <div style="margin-top: 20px;">
        <h4>结算明细</h4>
        <el-table :data="settlementDetails" border>
          <el-table-column prop="orderId" label="订单ID" />
          <el-table-column prop="amount" label="金额">
            <template #default="{ row }">
              ¥{{ formatMoney(row.amount) }}
            </template>
          </el-table-column>
          <el-table-column prop="commission" label="手续费">
            <template #default="{ row }">
              ¥{{ formatMoney(row.commission) }}
            </template>
          </el-table-column>
          <el-table-column prop="netAmount" label="净收入">
            <template #default="{ row }">
              ¥{{ formatMoney(row.netAmount) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Calendar, Money, Clock, Document, 
  Search, Refresh, CreditCard, Download 
} from '@element-plus/icons-vue'
import { 
  getSettlementList, 
  getSettlementDetail, 
  batchSettlement, 
  processSettlement, 
  retrySettlement, 
  exportSettlementReport, 
  exportSettlementDetail,
  getSettlementStats
} from '@/api/wash_service'

export default {
  name: 'FinanceSettlement',
  components: {
    Calendar, Money, Clock, Document,
    Search, Refresh, CreditCard, Download
  },
  setup() {
    const loading = ref(false)
    const batchLoading = ref(false)
    const batchDialogVisible = ref(false)
    const detailDialogVisible = ref(false)

    const stats = reactive({
      todaySettlement: 0,
      monthSettlement: 0,
      pendingAmount: 0,
      settlementCount: 0
    })

    const searchForm = reactive({
      period: '',
      status: '',
      dateRange: []
    })

    const pagination = reactive({
      current: 1,
      size: 20,
      total: 0
    })

    const tableData = ref([])
    const selectedRows = ref([])
    const currentSettlement = ref({})
    const settlementDetails = ref([])

    const batchForm = reactive({
      method: 'bank',
      remark: ''
    })

    const batchAmount = computed(() => {
      return selectedRows.value.reduce((sum, row) => sum + row.totalAmount, 0)
    })

    const periodMap = {
      daily: { text: '日结算', type: 'primary' },
      weekly: { text: '周结算', type: 'success' },
      monthly: { text: '月结算', type: 'warning' }
    }

    const statusMap = {
      pending: { text: '待结算', type: 'warning' },
      processing: { text: '结算中', type: 'primary' },
      completed: { text: '已结算', type: 'success' },
      failed: { text: '结算失败', type: 'danger' }
    }

    const formatMoney = (amount) => {
      return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }).format(amount)
    }

    const getPeriodText = (period) => periodMap[period]?.text || period
    const getPeriodType = (period) => periodMap[period]?.type || 'default'
    const getStatusText = (status) => statusMap[status]?.text || status
    const getStatusType = (status) => statusMap[status]?.type || 'default'

    const loadTableData = async () => {
      loading.value = true
      try {
        const params = {
          ...searchForm,
          page: pagination.current,
          size: pagination.size
        }
        
        const res = await getSettlementList(params)
        if (res && (res.code === 200 || res.data)) {
          const data = res.data || res
          tableData.value = data.records || data.content || data || []
          pagination.total = data.total || data.totalElements || 0
        } else {
          tableData.value = []
          pagination.total = 0
        }
      } catch (error) {
        console.error('获取结算数据失败:', error)
        ElMessage.warning('获取结算数据失败，请检查网络连接')
        tableData.value = []
        pagination.total = 0
      } finally {
        loading.value = false
      }
    }

    const loadSettlementDetails = async (settlementId) => {
      try {
        const res = await getSettlementDetail(settlementId)
        if (res && (res.code === 200 || res.data)) {
          const data = res.data || res
          settlementDetails.value = data.details || data || []
        } else {
          settlementDetails.value = []
        }
      } catch (error) {
        console.error('获取结算明细失败:', error)
        ElMessage.warning('获取结算明细失败')
        settlementDetails.value = []
      }
    }

    const handleSearch = () => {
      pagination.current = 1
      loadTableData()
    }

    const handleReset = () => {
      Object.assign(searchForm, {
        period: '',
        status: '',
        dateRange: []
      })
      handleSearch()
    }

    const handleSelectionChange = (selection) => {
      selectedRows.value = selection
    }

    const handleBatchSettle = () => {
      if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要结算的记录')
        return
      }
      
      const pendingRows = selectedRows.value.filter(row => row.status === 'pending')
      if (pendingRows.length === 0) {
        ElMessage.warning('所选记录中没有待结算的项目')
        return
      }
      
      selectedRows.value = pendingRows
      batchDialogVisible.value = true
    }

    const handleConfirmBatchSettle = async () => {
      try {
        batchLoading.value = true
        
        const settlementIds = selectedRows.value.map(row => row.settlementId)
        const res = await batchSettlement({
          settlementIds,
          method: batchForm.method,
          remark: batchForm.remark
        })
        
        if (res && (res.code === 200 || res.success)) {
          ElMessage.success(`成功结算 ${selectedRows.value.length} 条记录`)
          batchDialogVisible.value = false
          loadTableData()
        }
      } catch (error) {
        console.error('批量结算失败:', error)
        ElMessage.error('批量结算失败')
      } finally {
        batchLoading.value = false
      }
    }

    const handleSettle = async (row) => {
      try {
        await ElMessageBox.confirm('确定要执行结算操作吗？', '提示', {
          type: 'warning'
        })
        
        const res = await processSettlement(row.settlementId)
        if (res && (res.code === 200 || res.success)) {
          ElMessage.success('结算成功')
          loadTableData()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('结算失败:', error)
          ElMessage.error('结算失败')
        }
      }
    }

    const handleRetry = async (row) => {
      try {
        await ElMessageBox.confirm('确定要重试结算吗？', '提示', {
          type: 'warning'
        })
        
        const res = await retrySettlement(row.settlementId)
        if (res && (res.code === 200 || res.success)) {
          ElMessage.success('重试结算成功')
          loadTableData()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('重试失败:', error)
          ElMessage.error('重试失败')
        }
      }
    }

    const handleViewDetail = async (row) => {
      currentSettlement.value = row
      await loadSettlementDetails(row.settlementId)
      detailDialogVisible.value = true
    }

    const handleExport = async () => {
      try {
        const res = await exportSettlementReport({
          ...searchForm,
          format: 'excel'
        })
        if (res && (res.code === 200 || res.success)) {
          ElMessage.success('导出成功')
        }
      } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
      }
    }

    const handleExportDetail = async (row) => {
      try {
        const res = await exportSettlementDetail(row.settlementId)
        if (res && (res.code === 200 || res.success)) {
          ElMessage.success(`结算单 ${row.settlementId} 导出成功`)
        }
      } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
      }
    }

    // 获取结算统计数据
    const loadSettlementStats = async () => {
      try {
        const res = await getSettlementStats()
        if (res && (res.code === 200 || res.data)) {
          const data = res.data || res
          Object.assign(stats, {
            todaySettlement: data.todaySettlement || 0,
            monthSettlement: data.monthSettlement || 0,
            pendingAmount: data.pendingAmount || 0,
            settlementCount: data.settlementCount || 0
          })
        }
      } catch (error) {
        console.error('获取结算统计失败:', error)
        // 保持默认值0
      }
    }

    onMounted(() => {
      loadSettlementStats()
      loadTableData()
    })

    return {
      loading,
      batchLoading,
      batchDialogVisible,
      detailDialogVisible,
      stats,
      searchForm,
      pagination,
      tableData,
      selectedRows,
      currentSettlement,
      settlementDetails,
      batchForm,
      batchAmount,
      formatMoney,
      getPeriodText,
      getPeriodType,
      getStatusText,
      getStatusType,
      loadTableData,
      handleSearch,
      handleReset,
      handleSelectionChange,
      handleBatchSettle,
      handleConfirmBatchSettle,
      handleSettle,
      handleRetry,
      handleViewDetail,
      handleExport,
      handleExportDetail,
      loadSettlementStats
    }
  }
}
</script>

<style scoped>
.finance-settlement {
  padding: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  height: 100px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  font-size: 36px;
  margin-right: 15px;
  color: #909399;
}

.stat-icon.today {
  color: #409EFF;
}

.stat-icon.month {
  color: #67C23A;
}

.stat-icon.pending {
  color: #E6A23C;
}

.stat-icon.count {
  color: #F56C6C;
}

.stat-details h3 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.stat-details p {
  margin: 5px 0 0 0;
  color: #606266;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.amount-text {
  color: #67C23A;
  font-weight: bold;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.batch-info {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.batch-info p {
  margin: 0;
  margin-bottom: 5px;
}

.batch-info:last-child {
  margin-bottom: 0;
}
</style> 